package com.auth.controller;

import com.auth.constant.MessageConstant;
import com.auth.pojo.dto.SecurityUserDTO;
import com.auth.result.CommonResult;
import com.auth.service.impl.UserServiceImpl;
import com.auth.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * JWT认证控制器
 * 适配 Spring Boot 3.x 和 Spring Security 6.x
 */
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class JwtAuthController {

    private final AuthenticationManager authenticationManager;
    private final UserServiceImpl userService;
    private final JwtUtils jwtUtils;

    /**
     * 登录接口
     *
     * @param username 用户名
     * @param password 密码
     * @return 登录结果
     */
    @PostMapping("/login")
    public CommonResult<Map<String, Object>> login(@RequestParam String username, @RequestParam String password) {
        try {
            // 创建UsernamePasswordAuthenticationToken
            UsernamePasswordAuthenticationToken authenticationToken = 
                new UsernamePasswordAuthenticationToken(username, password);
            
            // 进行认证
            Authentication authentication = authenticationManager.authenticate(authenticationToken);
            
            // 保存认证信息
            SecurityContextHolder.getContext().setAuthentication(authentication);
            
            // 获取用户信息
            SecurityUserDTO userDetails = (SecurityUserDTO) authentication.getPrincipal();
            
            // 生成JWT令牌
            String token = jwtUtils.createToken(userDetails);
            
            // 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("tokenHead", "Bearer ");
            
            return CommonResult.success(result);
        } catch (Exception e) {
            return CommonResult.failed(MessageConstant.USERNAME_PASSWORD_ERROR);
        }
    }

    /**
     * 获取当前登录用户信息
     * 包含用户的菜单权限，用于前端动态路由生成
     *
     * @return 用户信息
     */
    @PostMapping("/info")
    public CommonResult<Map<String, Object>> getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return CommonResult.unauthorized(null);
        }
        
        // 获取当前登录用户
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        
        // 如果当前会话中的用户信息不完整，则重新加载
        if (!(userDetails instanceof SecurityUserDTO) || ((SecurityUserDTO) userDetails).getMenus() == null) {
            userDetails = userService.loadUserByUsername(userDetails.getUsername());
        }
        
        SecurityUserDTO securityUser = (SecurityUserDTO) userDetails;
        Map<String, Object> data = new HashMap<>();
        data.put("username", securityUser.getUsername());
        data.put("roles", securityUser.getAuthorities());
        data.put("menus", securityUser.getMenus());
        
        return CommonResult.success(data);
    }

    /**
     * 注销登录
     *
     * @return 注销结果
     */
    @PostMapping("/logout")
    public CommonResult<String> logout() {
        SecurityContextHolder.clearContext();
        return CommonResult.success("注销成功");
    }
}
